package com.lx.java8;

import java.util.concurrent.RecursiveTask;

/**
 * Java7中的并行计算
 * 定义一个用于拆分和合并的计算类
 * 这个类需要继承RecursiveAction（没有返回值）或者是RecursiveTask（有返回值）
 * @author liuxing
 *
 */
public class ForkCalculater extends RecursiveTask<Long> {
	private static final long serialVersionUID = -6790744108691400188L;
	private long start;
	private long end;

	private long boundary = 10000;

	public ForkCalculater() {
		super();
	}

	public ForkCalculater(long start, long end) {
		super();
		this.start = start;
		this.end = end;
	}

	@Override
	protected Long compute() {
		long length = end - start;
		if (length >= boundary) {
			long middle = (start + end) / 2;

			ForkCalculater left = new ForkCalculater(start, middle);
			left.fork(); //拆分，并将该子任务压入线程队列

			ForkCalculater right = new ForkCalculater(middle + 1, end);
			right.fork();

			return left.join() + right.join();
		} else {
			long sum = 0;

			for (long i = start; i <= end; i++) {
				sum += i;
			}
			return sum;
		}
	}

}
